package com.qf.weektest.weektest.service.impl;


import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.weektest.util.JWTUtil;
import com.qf.weektest.vo.Constants;
import com.qf.weektest.vo.ResultVo;
import com.qf.weektest.weektest.entity.Pollinf;
import com.qf.weektest.weektest.entity.Tel;
import com.qf.weektest.weektest.mapper.PollinfMapper;
import com.qf.weektest.weektest.service.IPollinfService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.weektest.weektest.service.ITelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljc
 * @since 2023-02-24
 */
@Service
public class PollinfServiceImpl extends ServiceImpl<PollinfMapper, Pollinf> implements IPollinfService {

    @Autowired
    ITelService iTelService;

    @Autowired
    ITelService telService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo poll(String telephone, String name, String token) throws UnsupportedEncodingException {

        Tel telephoneE = iTelService.getOne(new QueryWrapper<Tel>().eq("telephone", telephone));

        if (telephoneE == null || !telephoneE.getToken().equals(token)) {

            return ResultVo.erro("请携带token");
        }

        Pollinf pollinf = getOne(new QueryWrapper<Pollinf>().eq("name", name));

        long timeMillis = System.currentTimeMillis();

        if (pollinf == null) {

            save(new Pollinf(null, name, 1, telephone, timeMillis));

            telService.update(new UpdateWrapper<Tel>().eq("telephone",telephone).set("status",1));

            return ResultVo.ok("已添加选手");
        }

        if (timeMillis - pollinf.getTime() > 60000) {

            int count = pollinf.getPollCount() + 1;

            pollinf.setPollCount(count);

            pollinf.setTime(timeMillis);

            update(pollinf, new QueryWrapper<Pollinf>().eq("name", name));

            telService.update(new UpdateWrapper<Tel>().eq("telephone",telephone).set("status",1));

            return ResultVo.ok("以为他投票成功");
        }

        return ResultVo.erro("一分钟以后才能投票");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo countN() {

        List<Pollinf> list = list();

        Map<String, Integer> collect = list.stream().collect(Collectors.toMap(pollinf -> pollinf.getName(), pollinf -> pollinf.getPollCount()));

        return ResultVo.ok(collect);


    }
}
